from django.shortcuts import render

# Create your views here.

# 定义发送短信接口
# 1.请求方式
# 2.函数名
# 3.需要前端传递增样的数据　moblie
# 4.传递的路径
# 5.返回结果　ok

# 集成ＡＰＩＶiew
from rest_framework.generics import CreateAPIView,RetrieveAPIView, UpdateAPIView,GenericAPIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from user.models import User
from user.serializers import UserSerializer, UserDetailSerializer, UserEmailSerializer,VerifyEmailSerializer
from rest_framework.permissions import IsAuthenticated


class SMSCodeView(APIView):

    #　判断６０s

    # 获取数据　传递一个参数
    def get(self, request, mobile):
        sms_code = '%06d'%randint(0,999999)


        # 保存到verify中的　
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s'%mobile)
        if flag:
            return Response({'message':'error'},status=401)


        # 管道pl
        pl = conn.pipeline()
        # 建立连接　手机号码　有效期　写入数据内容
        pl.setex('sms_code_%s'%mobile,300,sms_code)
        # 写入１　的内容保存的时间未为６０秒
        pl.setex('sms_flag_%s'%mobile,60,1)
        pl.execute()
        # 发送短信 生成对象
        # ccp = CCP()
        # #  5--->有效期　１－－－＞模板
        # ccp.send_template_sms(mobile,[sms_code,'5'],1)
        # 使用celery的方法来发送短信
        send_sms_code.delay(mobile,sms_code)
        # 返回结果
        return Response({'message':'ok'})


class UserNameView(APIView):
    '''查询用户名，手机号码'''
    def get(slef,request,username):
        # 查询用户的数量
        count = User.objects.filter(username=username).count()
        return Response(
            {
                'username':username,
                'count':count,
            }
        )





class MobileView(APIView):
    '''查询手机号码'''
    def get(slef,request,mobile):
        # 查询用户的数量
        count = User.objects.filter(mobile=mobile).count()
        return Response(
            {
                'mobile':mobile,
                'count':count,
            }
        )


class UserView(CreateAPIView):
    '''保存用户数据'''
    serializer_class = UserSerializer


class UserDetailView(RetrieveAPIView):
    '''用户登录页面的接口'''
    # 因为RetrieveAPIView实现了获取用户前端数据，数据验证，数据更新的
    # 方法，因次继承便好
    serializer_class = UserDetailSerializer
    #　认证用户，到底是匿名用户，还是登录用户
    permission_classes = [IsAuthenticated]

    # 重写get_object方法返回指定数据对象
    def get_object(self):
        # request是属性，具有.data可以获取该请求体的数据，这.user是获取user对象，根据这个去赋值给
        # self.requset
        print(self.request.user)
        return self.request.user

class UserEmailView(UpdateAPIView):
    '''修改用户信息'''
    serializer_class = UserEmailSerializer
    permission_classes = [IsAuthenticated]

    # 重写get_object方法返回指定数据对象
    def get_object(self):
        print(self.request.user)
        # 获取用户对象.
        return self.request.user

    # def put(self,request,*args,**kwargs):
        # ser = UserEmailSerializer(request.user,data=request.data,context={'request':request,'mobile':13211111111})
        # # 这里不需要验证，因为email字段已经验证了
        # ser.is_valid()
        # # 只要是保存，就会调用update()
        # ser.save()
        # return Response(ser.data)



class VerifyEmailView(GenericAPIView):
    serializer_class = VerifyEmailSerializer

    def get(self,request):
        #　获取数据
        data = request.query_params
        # 数据验证
        ser = self.get_serializer(data=data)
        ser.is_valid()
        print(ser.errors)

        data = ser.validated_data['data']
        id = data['id']
        username = data['username']
        try:
            user = User.objects.get(id=id,username=username)
        except:
            return Response({'errors':'用户不存在'},status=400)
        user.email_active = True
        user.save()

        return Response({'email_active':True})



















